package com.lu.adog.base;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AppCompatActivity;

import com.lu.adog.util.Logg;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author Yue
 * @date 2017/11/13 18:15
 */

public class BaseActivity extends AppCompatActivity {
    public interface PermissonCallback {
        void callBack(boolean hasPer, String permissions[], int[] grantResults);
    }

    private int okCode = 10001;

    //    private new String[]{Manifest.permission.CAMERA}
    private PermissonCallback mPermissonCallback;

    public void requirePermisson(int okCode, String[] permissions, PermissonCallback permissonCallback) {
        mPermissonCallback = permissonCallback;
        this.okCode = okCode;
        boolean has = true;
        for (String p : permissions) {
            if (PermissionChecker.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) {
                has = false;
                break;
            }
        }
        if (has) {
            permissonCallback.callBack(true, permissions, null);
        } else {
            ActivityCompat.requestPermissions(this, permissions, okCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mPermissonCallback != null) {

            if (requestCode == okCode && grantResults.length > 0) {

                for (int grant : grantResults) {
                    if (grant != PackageManager.PERMISSION_GRANTED) {
                        mPermissonCallback.callBack(false, permissions, grantResults);
                        return;
                    }

                }
                mPermissonCallback.callBack(true, permissions, grantResults);
            } else {
                mPermissonCallback.callBack(false, permissions, grantResults);
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        BaseApp.getBaseApp().addActivity(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApp.getBaseApp().removeActivity(this);
    }
}
